package com.example.api.service.impl;

import com.example.api.constant.StatusConst;
import com.example.api.dto.CategoryDTO;
import com.example.api.exception.BusException;
import com.example.api.mapper.CategoryMapper;
import com.example.api.pojo.Category;
import com.example.api.query.CategoryQuery;
import com.example.api.service.CategoryService;
import com.example.api.service.FoodService;
import com.example.api.utils.PageResult;
import com.example.api.vo.CategoryDetailVO;
import com.example.api.vo.CategoryVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {


    @Resource
    CategoryMapper categoryMapper;

    @Resource
    FoodService foodService;



    @Override
    public PageResult<CategoryVO> find(CategoryQuery categoryQuery) {

        //设置是否需要分页
        PageHelper.startPage(categoryQuery.getPage(),categoryQuery.getPageSize());  //告诉PageHelper此处需要分页

        //List
        Page<CategoryVO> page = (Page<CategoryVO>) categoryMapper.find(categoryQuery);

        PageInfo<CategoryVO> pageInfo = page.toPageInfo();


        List<CategoryVO> categoryVOList = pageInfo.getList();
        long total = pageInfo.getTotal();

        PageResult<CategoryVO> pageResult = new PageResult<>();
        pageResult.setTotal(total);
        pageResult.setList(categoryVOList);

        return pageResult;
    }

    @Override
    public void add(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);

        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());

        category.setStatus(StatusConst.ACTIVE_STATUS);

        categoryMapper.add(category);
    }


    @Override
    public void update(long id, CategoryDTO categoryDTO) {
        //dto -- > pojo
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);

        category.setId(id);
        category.setUpdateTime(new Date());
        categoryMapper.update(category);
    }

    @Override
    public void deleteById(long id) {
        //TODO 为什么需要判断当前分类下面是否已经有菜品,如果有需要先删除菜品？
        int count = foodService.findCountByCategoryId(id);
        if(count>0){
            throw new BusException("当前分类下存在菜品");
        }
        categoryMapper.deleteById(id);
    }

    @Override
    public void updateStatus(long id, byte status) {
        Category category = new Category();
        category.setId(id);
        category.setStatus(status);
        category.setUpdateTime(new Date());
        categoryMapper.update(category);
    }

    @Override
    public List<CategoryDetailVO> findCategoryAndFood(int shopId) {
        return  categoryMapper.findCategoryAndFood();
    }
}